package com.wangcanxuan.www.service.Impl;

import com.wangcanxuan.www.dao.mapper.NoticeMapper;
import com.wangcanxuan.www.dao.mapper.UserMapper;
import com.wangcanxuan.www.entity.dto.ResultInfo;
import com.wangcanxuan.www.entity.po.Notice;
import com.wangcanxuan.www.entity.po.User;
import com.wangcanxuan.www.exception.ServiceException;
import com.wangcanxuan.www.proxy.DaoProxy;
import com.wangcanxuan.www.service.NoticeService;
import com.wangcanxuan.www.util.SecurityUtil;

import java.time.LocalDateTime;
import java.util.List;

import static com.wangcanxuan.www.entity.dto.ResultConstants.SUCCESS_REQUEST_CODE;

/**
 * 通知业务实现类
 *
 * @author HHLJ
 * @date 2022/04/08
 */
public class NoticeServiceImpl implements NoticeService {
    private final NoticeMapper NOTICE_MAPPER = DaoProxy.getMapper(NoticeMapper.class);

    @Override
    public ResultInfo<List<Notice>> getNotices(String userId, int pageCount) {
        // 通过用户id来获取当前所有通知
        List<Notice> notices = NOTICE_MAPPER.selectNoticeList(userId, pageCount);
        // 如果没有通知
        if (notices.size() == 0 && pageCount == 0) {
            return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(),notices);
        }
        if (notices.size() == 0) {
            return ResultInfo.operateRejectWithMessage("这是尾页！");
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode(),notices);
    }

    @Override
    public ResultInfo<String> finishNotice(String chooseNoticeId) {
        // 通过选择通知的id查询到当前通知
        Notice notice = new Notice();
        notice.setId(chooseNoticeId);
        notice = NOTICE_MAPPER.selectById(notice);

        // 删除该通知
        int delete = NOTICE_MAPPER.delete(notice);
        if (delete != 1) {
            throw new ServiceException("通知已阅功能异常");
        }
        return new ResultInfo<>(SUCCESS_REQUEST_CODE.getCode());
    }

    public static void setNoticeForUser(User user, String noticeType, String noticeContent) {
        // 设置通知给用户
        UserMapper userMapper = DaoProxy.getMapper(UserMapper.class);
        NoticeMapper noticeMapper = DaoProxy.getMapper(NoticeMapper.class);

        if (user == null) {
            return;
        }

        // 通过用户id搜索当前用户
        user = userMapper.selectById(new User(user.getId()));

        // 创建通知
        Notice notice = new Notice();
        notice.setId(SecurityUtil.uuidCreateId());
        notice.setUserId(user.getId());
        notice.setNoticeType(noticeType);
        notice.setContent(noticeContent);
        notice.setCreateTime(LocalDateTime.now());

        // 将通知插入数据库
        int insert = noticeMapper.insert(notice);
        if (insert != 1) {
            throw new ServiceException("发布通知功能异常");
        }
    }
}
